<?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use App\Models\Product;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Validator;
use Illuminate\Validation\Rule;

class ProductController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        try {
            $products = Product::all();
            return response()->json([
                'success' => true,
                'data' => $products
            ], 200);
        } catch (\Exception $e) {
            return response()->json([
                'success' => false,
                'message' => 'Failed to retrieve products',
                'error' => $e->getMessage()
            ], 500);
        }
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request)
    {
        try {
            // 数据验证
            $validator = Validator::make($request->all(), [
                'name' => 'required|string|max:255',
                'price' => 'required|numeric|min:0',
                'source' => ['required', Rule::in(['A', 'B'])],
            ]);

            if ($validator->fails()) {
                return response()->json([
                    'success' => false,
                    'message' => 'Validation failed',
                    'errors' => $validator->errors()
                ], 422);
            }

            // 创建产品
            $product = Product::create($request->only(['name', 'price', 'source']));

            return response()->json([
                'success' => true,
                'message' => 'Product created successfully',
                'data' => $product
            ], 201);
        } catch (\Exception $e) {
            return response()->json([
                'success' => false,
                'message' => 'Failed to create product',
                'error' => $e->getMessage()
            ], 500);
        }
    }

    /**
     * Display the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function show($id)
    {
        try {
            $product = Product::findOrFail($id);

            return response()->json([
                'success' => true,
                'data' => $product
            ], 200);
        } catch (\Illuminate\Database\Eloquent\ModelNotFoundException $e) {
            return response()->json([
                'success' => false,
                'message' => 'Product not found'
            ], 404);
        } catch (\Exception $e) {
            return response()->json([
                'success' => false,
                'message' => 'Failed to retrieve product',
                'error' => $e->getMessage()
            ], 500);
        }
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function update(Request $request, $id)
    {
        try {
            $product = Product::findOrFail($id);

            // 数据验证
            $validator = Validator::make($request->all(), [
                'name' => 'sometimes|required|string|max:255',
                'price' => 'sometimes|required|numeric|min:0',
                'source' => ['sometimes', 'required', Rule::in(['A', 'B'])],
            ]);

            if ($validator->fails()) {
                return response()->json([
                    'success' => false,
                    'message' => 'Validation failed',
                    'errors' => $validator->errors()
                ], 422);
            }

            // 更新产品
            $product->update($request->only(['name', 'price', 'source']));

            return response()->json([
                'success' => true,
                'message' => 'Product updated successfully',
                'data' => $product
            ], 200);
        } catch (\Illuminate\Database\Eloquent\ModelNotFoundException $e) {
            return response()->json([
                'success' => false,
                'message' => 'Product not found'
            ], 404);
        } catch (\Exception $e) {
            return response()->json([
                'success' => false,
                'message' => 'Failed to update product',
                'error' => $e->getMessage()
            ], 500);
        }
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function destroy($id)
    {
        try {
            $product = Product::findOrFail($id);
            $product->delete();

            return response()->json([
                'success' => true,
                'message' => 'Product deleted successfully'
            ], 200);
        } catch (\Illuminate\Database\Eloquent\ModelNotFoundException $e) {
            return response()->json([
                'success' => false,
                'message' => 'Product not found'
            ], 404);
        } catch (\Exception $e) {
            return response()->json([
                'success' => false,
                'message' => 'Failed to delete product',
                'error' => $e->getMessage()
            ], 500);
        }
    }

    /**
     * 同步供应商产品数据
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function syncProducts(Request $request)
    {
        try {
            // 验证请求中是否包含供应商产品数据
            $validator = Validator::make($request->all(), [
                'source' => ['required', Rule::in(['A', 'B'])],
                'products' => 'required|array'
            ]);

            if ($validator->fails()) {
                return response()->json([
                    'success' => false,
                    'message' => 'Validation failed',
                    'errors' => $validator->errors()
                ], 422);
            }

            $source = $request->input('source');
            $productsData = $request->input('products');
            $createdCount = 0;
            $updatedCount = 0;

            // 根据不同的供应商格式进行数据映射
            foreach ($productsData as $productData) {
                // 数据映射逻辑
                $mappedData = [];
                if ($source === 'A') {
                    // 供应商A的格式: {"id":整数,"name":字符串,"sell price":浮点数}
                    $mappedData = [
                        'name' => $productData['name'] ?? '',
                        'price' => $productData['sell price'] ?? 0,
                        'source' => 'A'
                    ];
                } elseif ($source === 'B') {
                    // 供应商B的格式: {"pid":整数,"good_name":字符串,"rrp_price":浮点数}
                    $mappedData = [
                        'name' => $productData['good_name'] ?? '',
                        'price' => $productData['rrp_price'] ?? 0,
                        'source' => 'B'
                    ];
                }

                // 验证映射后的数据
                $productValidator = Validator::make($mappedData, [
                    'name' => 'required|string|max:255',
                    'price' => 'required|numeric|min:0'
                ]);

                if ($productValidator->fails()) {
                    continue; // 跳过无效数据
                }

                // 检查是否已存在该产品
                $existingProduct = Product::where('name', $mappedData['name'])
                    ->where('source', $source)
                    ->first();

                if ($existingProduct) {
                    // 更新现有产品
                    $existingProduct->update($mappedData);
                    $updatedCount++;
                } else {
                    // 创建新产品
                    Product::create($mappedData);
                    $createdCount++;
                }
            }

            return response()->json([
                'success' => true,
                'message' => 'Products synced successfully',
                'data' => [
                    'created' => $createdCount,
                    'updated' => $updatedCount,
                    'source' => $source
                ]
            ], 200);
        } catch (\Exception $e) {
            return response()->json([
                'success' => false,
                'message' => 'Failed to sync products',
                'error' => $e->getMessage()
            ], 500);
        }
    }
};